/**
 * Created by Peter on 2016/4/27.
 */

define(['jquery', 'domReady!', 'appLocalStorage', 'appConst', 'model/global', 'appMessageBox'], function ($, domReady, appLocalStorage, appConst, global, msgBox) {
    var searchFields = {};
    var type = {};
    var search_key = appConst.searchKey.search_user_key + global.getUserId();
    var that;
    return {
        init: function () {
            that = this;
        },
        getSearchFields: function () {
            return searchFields;
        },
        setSearchFields: function (obj) {
            searchFields = {};
            $.extend(searchFields, obj);
        },
        getType: function () {
            return type;
        },
        setType: function (obj) {
            $.extend(type, obj);
        },
        runDataTables: function () {
            that.setSearchCondition();
            var customParams = function (params) {
                $.extend(params, that.getSearchFields());
                params['draw'] = params.draw;
                return params;
            };

            var dt_users = $('#dt_users').dataTable({
                "sDom": "<'dt-toolbar'<'col-xs-12 col-sm-6'><'col-sm-6 col-xs-12 hidden-xs'>>r" +
                "t" +
                "<'dt-toolbar-footer'<'col-sm-6 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-6'p>>",
                "processing": true,
                "pageLength": global.getPageSize(),
                "paging": true,
                //"paging": true,
                //"pagingType":   "full_numbers",
                "autoWidth": false,
                "serverSide": true,
                "language": appConst.table_language(),
                "stateSave": true,
                "ordering": false,
                "ajax": {
                    "url": 'user/list',
                    "type": "POST",
                    "dataSrc": "body",
                    "traditional": true,
                    "data": customParams,
                    "error": function (e) {
                        if (e.status == 401) {
                            msgBox.sessionFailureBox();
                        }
                        if (e.status == 500) {
                            msgBox.serverFailureBox();
                        }
                        if (e.status == 404) {
                            msgBox.pathFailureBox();
                        }
                    }
                },
                //"deferRender": true,
                "columns": [
                    {"data": null},
                    {"data": "id"},
                    {"data": "loginName"},
                    {"data": "name"},
                    {"data": "email"},
                    {"data": "status"},
                    {"data": null}
                ],
                "columnDefs": [
                    {
                        "targets": [1],
                        "visible": false
                    },
                    {
                        "targets": [5],
                        "render": function (data, type, full) {
                            var status = '';
                            if (full.status == 'ACTIVE') {
                                status = '<span class="label label-success">' + $.i18n.prop('USER_STATUS_ACTIVE') + '</span>';
                            } else if (full.status == 'LOCK') {
                                status = '<span class="label label-warning">' + $.i18n.prop('USER_STATUS_LOCK') + '</span>';
                            }
                            else if (full.status == 'DISABLE') {
                                status = '<span class="label label-danger">' + $.i18n.prop('USER_STATUS_DISABLE') + '</span>';
                            }
                            return status;
                        }
                    },
                    {
                        "targets": [6],
                        "render": function (data, type, full) {
                            var id = full.id;
                            //var name = full.name;

                            var obj = JSON.stringify({
                                "id": full.id,
                                "name": full.name,
                                "loginName": full.loginName,
                                "email": full.email,
                                "status": full.status
                            });

                            var isDefault = full.isDefault;
                            var aHref = "";
                            if (isDefault == false) {
                                aHref = '<a href="javascript:void(0);" class="deleteUserConfirm" id="' + id + '" >' + $.i18n.prop("GLOBAL_DELETE") + '</a> '
                            }
                            else {
                                aHref = "";
                            }

                            var url = "#user/edit/" + id;

                            var operate = '<div class="center">'
                                + '<a href="javascript:void(0);" class="details-control">' + $.i18n.prop('MENU_SYSTEM_ROLE') + '</a> '
                                + "<a href='" + url + "'>" + $.i18n.prop("GLOBAL_EDIT") + "</a> "
                                + aHref
                                + "<a href='javascript:void(0);' class='resetPasswordConfirm' obj='" + obj + "' title='" + $.i18n.prop("USER_TITEL_EMAIL") + "'>" + $.i18n.prop("GLOBAL_RESET_PASSWORD") + "</a>"
                                + "</div>";
                            return operate;
                        }
                    }
                ]
            });

            global.drawNumber_bg($('#dt_users'), function () {
                $('#dt_users').find(".deleteUserConfirm").unbind('click').on('click', function (obj) {
                    that.deleteUserConfirm($(this).attr("id"));
                });
                $('#dt_users').find(".resetPasswordConfirm").unbind('click').on('click', function (obj) {
                    that.resetPasswordConfirm($(this).attr("obj"));
                });
            });

            // Add event listener for opening and closing details
            $('#dt_users tbody').on('click', 'a.details-control', function () {
                var tr = $(this).closest('tr');
                var row = $('#dt_users').DataTable().row(tr);
                if (row.child.isShown()) {
                    // This row is already open - close it
                    row.child.hide();
                    tr.removeClass('shown');

                }
                else {
                    reShowRole();
                    // Open this row
                    function assignRole() {
                        tr.next('tr').find('.addRole').unbind('click').click(function (e) {
                            if ($(this).hasClass("btn-warning")) {
                                $(this).removeClass("btn-warning");
                                $(this).addClass("btn-danger addDanger");
                            } else if ($(this).hasClass("btn-danger")) {
                                $(this).removeClass("btn-danger");
                                $(this).addClass("btn-warning");
                            }
                        });
                        tr.next('tr').find('.hasRole').unbind('click').click(function (e) {
                            if ($(this).hasClass("btn-info")) {
                                $(this).removeClass("btn-info");
                                $(this).addClass("btn-danger minusDanger");
                            } else if ($(this).hasClass("btn-danger")) {
                                $(this).removeClass("btn-danger");
                                $(this).addClass("btn-info");
                            }
                        });
                        tr.next('tr').find('.plus').unbind('click').click(function (e) {
                            if (tr.next('tr').find('.addRole').hasClass("btn-danger")) {
                                var userId = "";
                                var roleId = new Array();
                                userId = row.data().id;
                                tr.next('tr').find('.addDanger').each(function (i, e) {
                                    roleId.push($(this).val());
                                });
                                $.ajax({
                                    "type": "post",
                                    "url": 'user/assignRole',
                                    "dataType": "json",
                                    "data": {'userId': userId, 'roleId': roleId.toString()},
                                    "success": function (d) {
                                        if (d.code == 0) {
                                            msgBox.errorBox('DELETE_FAIL');
                                            return false;
                                        }

                                        reShowRole();
                                    },
                                    "error": function (e) {
                                        if (e.status == 401) {
                                            msgBox.sessionFailureBox();
                                        }
                                        if (e.status == 500) {
                                            msgBox.serverFailureBox();
                                        }
                                        if (e.status == 404) {
                                            msgBox.pathFailureBox();
                                        }
                                    }
                                });
                            } else {
                                return false;
                            }
                        });
                        tr.next('tr').find('.minus').unbind('click').click(function (e) {
                            if (tr.next('tr').find('.hasRole').hasClass("btn-danger")) {
                                var userId = "";
                                var roleId = new Array();
                                userId = row.data().id;
                                tr.next('tr').find('.minusDanger').each(function (i, e) {
                                    roleId.push($(this).val());
                                });
                                var assignRole = $.ajax({
                                    "type": "post",
                                    "url": 'user/deleteRole',
                                    "dataType": "json",
                                    "data": {'userId': userId, 'roleId': roleId.toString()},
                                    "success": function (e) {
                                        reShowRole();
                                    },
                                    "error": function (e) {
                                        if (e.status == 401) {
                                            msgBox.sessionFailureBox();
                                        }
                                        if (e.status == 500) {
                                            msgBox.serverFailureBox();
                                        }
                                        if (e.status == 404) {
                                            msgBox.pathFailureBox();
                                        }
                                    }
                                });
                            } else {
                                return false;
                            }
                        });
                    }
                }
                function reShowRole() {
                    var findUserCanAddRoles = $.ajax({
                        "url": "user/findUserCanAddRoles/" + row.data().id,
                        "type": "POST",
                        "success": function (notHave) {
                            row.child(format(notHave.body.userHaveRoleDtos, notHave.body.findUserCanAddRoles), "subGrid").show();
                            tr.addClass('shown');
                            assignRole();
                        }
                    });
                }
            });
            function format(have, notHave) {
                var canAddrole = "";
                var haverole = "";
                $(notHave).each(function (i, e) {
                    canAddrole += '<button class="btn btn-xs btn-warning pull-left addRole" value="' + e.id + '">' + e.name + "</button>";
                });
                $(have).each(function (i, e) {
                    haverole += '<button class="btn btn-xs btn-info pull-left hasRole" value="' + e.id + '">' + e.name + "</button>";
                });
                return '<table class="table" id="buttstatus">' +
                    '<tr>' +
                    '<td class="pull-left">' + $.i18n.prop('USER_CAN_ADD_ROLE') + '&nbsp</td>' +
                    '<td class="pull-left">' +
                    '<a href="javascript:void(0);" class="btn btn-success btn-xs plus"><i class="fa fa-plus"></i></a>'
                    + canAddrole +
                    '</td>' +
                    '</tr>' +
                    '<tr>' +
                    '<td class="pull-left">' + $.i18n.prop('USER_HAVE_ROLE') + '</td>' +
                    '<td class="pull-left">' +
                    '<a href="javascript:void(0);" class="btn btn-success btn-xs minus"><i class="fa fa-minus"></i></a>'
                    + haverole +
                    '</td>' +
                    '</tr>' +
                    '</table> '
                    ;
            }
        },
        initBasicSearchEvent: function () {
            $('#btn-simple-search').click(function (e) {
                var searchparam = {
                    'search_LIKE_loginName': $('#loginName').val(),
                    'search_LIKE_name': $('#name').val(),
                    'search_LIKE_email': $('#email').val()
                };
                that.setSearchFields(searchparam);
                appLocalStorage.setLocal(search_key, JSON.stringify(searchparam));
                $('#dt_users').DataTable().draw();
            });

            // document.onkeyup = function (event) {
            //     var e = event || window.event || arguments.callee.caller.arguments[0];
            //     if (e && e.keyCode == 13) { // enter 键
            //         var searchparam = {
            //             'search_LIKE_loginName': $('#loginName').val(),
            //             'search_LIKE_name': $('#name').val(),
            //             'search_LIKE_email': $('#email').val()
            //         };
            //         that.setSearchFields(searchparam);
            //         appLocalStorage.setLocal(search_key, JSON.stringify(searchparam));
            //         $('#dt_users').DataTable().draw();
            //     }
            // };

            that.setSearchCondition();
        },
        setSearchCondition: function () {
            var queryParameter = appLocalStorage.getLocal(search_key);

            if (queryParameter != null) {
                queryParameter = JSON.parse(queryParameter);
                var qLoginName = queryParameter.search_LIKE_loginName;
                if (qLoginName != "") {
                    $("#loginName").val(qLoginName);
                }

                var qName = queryParameter.search_LIKE_name;
                if (qName != "") {
                    $("#name").val(qName);
                }

                var qEmail = queryParameter.search_LIKE_email;
                if (qEmail != "") {
                    $("#email").val(qEmail);
                }
            }
            this.setSearchFields(queryParameter);
        },
        deleteUserConfirm: function (id) {
            if ($("a").hasClass('btn-resetp')) {
                $(".btn-resetp").trigger("click");
            }
            msgBox.show({
                title: $.i18n.prop('MESSAGEBOX_CONFIRM_TITLE'),
                content: "" + $.i18n.prop("USER_DELETE_SUBMIT") + " <p class='text-align-right'>" +
                "<button type='submit' data-id='"+ id + "' class='btn btn-primary btn-sm deleteUser"+ id +"'>" + $.i18n.prop("GLOBAL_BUTTON_YES") + "</button> " +
                "<a href='javascript:void(0);' class='btn btn-danger btn-sm btn-delete'>" + $.i18n.prop("GLOBAL_BUTTON_NO") + "</a></p>",
                type: 'normal',
                timeout: false,
                clean: true
            });

            $('#divSmallBoxes').find(".deleteUser" + id).unbind('click').on('click', function (e) {
                e.preventDefault();
                that.deleteUser($(this).attr("data-id"));
            });
        },
        deleteUser: function (id) {
            $.ajax({
                "url": "user/delete/" + id,
                "type": "POST",
                "success": function (d) {
                    if (d.code == 0) {
                        msgBox.errorBox(d.message != null ? d.message : 'USER_DELETE_FAIL', 'MENU_SYSTEM_USER');
                        return false;
                    } else {
                        msgBox.successBox({
                            content: $.i18n.prop('USER_DELETE_SUCCESS')
                        });
                    }

                    $('#dt_users').DataTable().draw();
                },
                "error": function (e) {
                    if (e.status == 401) {
                        msgBox.sessionFailureBox();
                    }
                    if (e.status == 500) {
                        msgBox.serverFailureBox();
                    }
                    if (e.status == 404) {
                        msgBox.pathFailureBox();
                    }
                }
            });
        },
        resetPassword: function (id) {
            $.ajax({
                "url": "user/resetPassword/" + id,
                "type": "post",
                "success": function (d) {
                    if (d.code == 0) {
                        msgBox.errorBox(d.message != null ? d.message : 'USER_PASSWORD_FAIL', 'MENU_SYSTEM_USER');
                        return false;
                    } else {
                        msgBox.successBox({
                            content: $.i18n.prop('USER_PASSWORD_SUCCESS')
                        });
                    }

                },
                "error": function (e) {
                    if (e.status == 401) {
                        msgBox.sessionFailureBox();
                    }
                    if (e.status == 500) {
                        msgBox.serverFailureBox();
                    }
                    if (e.status == 404) {
                        msgBox.pathFailureBox();
                    }
                }
            });
        },
        resetPasswordConfirm: function (jsonString) {
            var obj = JSON.parse(jsonString);
            var id = obj.id;
            var name = obj.name;

            if ($("a").hasClass("btn-delete")) {
                $(".btn-delete").trigger("click");
            }
            msgBox.show({
                title: $.i18n.prop('MESSAGEBOX_CONFIRM_TITLE'),
                content: "" + $.i18n.prop("USER_RESETPASSWORD_MESSAGE") + " " + name + "  <p class='text-align-right'>" +
                "<a href='javascript:void(0);' data-id='" + id + "' class='btn btn-primary btn-sm resetPassword"+ id +"'>" + $.i18n.prop("GLOBAL_BUTTON_YES") + "</a> " +
                "<a href='javascript:void(0);' class='btn btn-danger btn-sm btn-resetp'>" + $.i18n.prop("GLOBAL_BUTTON_NO") + "</a></p>",
                type: 'normal',
                timeout: false,
                clean: true
            });

            $('#divSmallBoxes').find(".resetPassword" + id).unbind('click').on('click', function (e) {
                e.preventDefault();
                that.resetPassword($(this).attr("data-id"));
            });
        }
    }
});
